package com.flower.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.flower.pojo.Cart;
import com.flower.pojo.CartItem;
import com.flower.pojo.Product;
import com.flower.pojo.User;
import com.flower.service.ICartService;

/**
 *	购物车模块
 */
@Controller
public class CartController {
	
	@Resource(name = "cartService")
	private ICartService iCartService;
	//购物项列表
	private List<CartItem> items;
	
	/**
	 * 加入购物车中
	 * @throws Exception 
	 */
	@RequestMapping("/addCart.do")
	public String addCart(HttpServletRequest request, Model model, String currentUrl,
			HttpServletResponse response) throws Exception{
		//判断是否登录
		//从session中获取用户
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			Cookie cookie = new Cookie("URL", currentUrl);
			response.addCookie(cookie);
			return "redirect:/login.jsp";
		}
		
	   
		Product product = (Product) request.getSession().getAttribute("PRODUCT");
		int num = Integer.parseInt(request.getParameter("num"));
		
		items = iCartService.getAllCartItem(user.getUid());
		
		if(items != null || items.size() > 0){
			//重新登录，且有数据时，重构购物车
			Cart cart = new Cart();
			Map<Integer, CartItem> map = cart.getMap();
			for(CartItem cartItem: items){
				map.put(cartItem.getProduct().getPid(), cartItem);
			}
			
			request.getSession().setAttribute("CART", cart);
		}
		
		//从session(具有有效期，退出时 session销毁)中获取cart
		Cart cart = (Cart) request.getSession(true).getAttribute("CART");
		
		//购物车为空时
		if(cart == null){
			//创建购物车
			cart = new Cart();
			Map<Integer, CartItem> map = cart.getMap();
			CartItem cartItem = map.get(product.getPid());
			
			map.put(product.getPid(), iCartService.addCart(num, cartItem, product, user));
			//使用session同步存储数据
			request.getSession().setAttribute("CART", cart);
			
			//重定向到cart.jsp：显示页面，不更新数据
		}else{
			if(num == 0){
				return "redirect:/cart.jsp";
			}
			CartItem cartItem = iCartService.getCartItem(user.getUid(), product.getPid());

			//若此用户购物车中的某购物项为空时
			if(cartItem == null){
				//添加
				cart.getMap().put(product.getPid(), iCartService.addCart(num, cartItem, product, user));
			}else{
				//更新数据库
				iCartService.updateCartItem(num, num * product.getShop_price(), user.getUid(), product.getPid());
				//更新map
				cart.getMap().get(product.getPid()).setPnum(num);
				cart.getMap().get(product.getPid()).setSubTotal(num * product.getShop_price());
			}
		}
		
		return "redirect:/cart.jsp";
	}

	/**
	 * 删除该用户的某一个购物项
	 */
	@RequestMapping("/delProduct.do")
	public String delProduct(HttpServletRequest request){
		Cart cart = (Cart) request.getSession(true).getAttribute("CART");
		User user = (User) request.getSession().getAttribute("USER");
		int pid = Integer.parseInt(request.getParameter("pid"));
		
		//数据库：删除
		iCartService.deleteCartItem(user.getUid(), pid);
		//session：删除（达到同步）
		cart.getMap().remove(pid);
		
		return "redirect:/cart.jsp";
	}
	
	/**
	 * 清空购物车
	 */
	@RequestMapping("/clearCart.do")
	public String clearCart(HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("USER");
		Cart cart = (Cart) request.getSession(true).getAttribute("CART");
		
		iCartService.clearCart(user.getUid());
		cart.setMap(null);
		
		return "redirect:/cart.jsp";
	}
	
	
	/**
	 * 更新购买数量的值
	 */
	@RequestMapping("/updatePnum.do")
	public String updatePnum(HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("USER");
		Cart cart = (Cart) request.getSession(true).getAttribute("CART");
		int pid = Integer.parseInt(request.getParameter("pid"));
		int num = Integer.parseInt(request.getParameter("num"));
		
		double subTotal = num * cart.getMap().get(pid).getProduct().getShop_price();
		iCartService.updateCartItem(num, subTotal , user.getUid(), pid);
		cart.getMap().get(pid).setPnum(num);
		cart.getMap().get(pid).setSubTotal(subTotal);
		
		return "redirect:/cart.jsp";
	}
}
